import base64
import os

from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ
from users.models import User


class QQAuthCallBackSerializer(serializers.ModelSerializer):
    """QQ登录用户数据保存序列化器"""
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    access_token = serializers.CharField(label='加密的openid', write_only=True)
    token = serializers.CharField(label='JWTToken', read_only=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$', write_only=True)

    class Meta:
        model = User
        fields = ('id', 'mobile', 'password', 'sms_code', 'access_token', 'token', 'username')

        extra_kwargs = {
            'username': {
                'read_only': True
            },
            'password': {
                'write_only': True,
            }
        }

    # 校验完整性,校验短信验证码,校验access_token有效性
    def validate(self, attrs):
        # 校验access_token有效性
        access_token = attrs['access_token']
        openid = OAuthQQ.check_save_user_token(token=access_token)

        if openid is None:
            return serializers.ValidationError('无效的access_token')

        # 增加openid,create增加数据时候validated_data中取数据使用
        attrs['openid'] = openid

        # 校验短信验证码是否正确
        sms_code = attrs['sms_code']
        mobile = attrs['mobile']

        conn = get_redis_connection('verify_codes')
        real_sms_code = conn.get('sms_code_%s' % mobile)

        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码过期')

        # 验证码校验
        if sms_code != real_sms_code.decode():
            raise serializers.ValidationError('短验证码错误')

        # 如果手机号已经被注册,校验对应密码是否正确
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 用户未注册过
            user = None
        else:
            # 用户注册过
            # 校验密码
            password = attrs['password']
            if not user.check_password(password):
                raise serializers.ValidationError('登陆密码错误')

        # 向attrs中添加user属性,创建用户时可以直接使用
        attrs['user'] = user
        return attrs

    def create(self, validated_data):
        # 创建QQ登录用户信息
        user = validated_data.get('user')
        openid = validated_data.get('openid')

        # # 先判断用户是否存在
        # if user:
        #     # 用户存在
        #     OAuthQQUser.objects.create(user=user, openid=openid)
        # else:
        #     # 用户不存在,先创建用户对象
        #     # 先生成随机用户名使用
        #     username = base64.b64encode(os.urandom(6)).decode()
        #     password = validated_data.get('password')
        #     mobile = validated_data.get('mobile')
        #     user = User.objects.create_user(username=username, password=password, mobile=mobile)
        #
        #     OAuthQQUser.objects.create(user=user, openid=openid)

        if user is None:
            # 用户不存在,先创建用户对象
            # 先生成随机用户名使用
            username = base64.b64encode(os.urandom(6)).decode()
            password = validated_data.get('password')
            mobile = validated_data.get('mobile')
            user = User.objects.create_user(username=username, password=password, mobile=mobile)

        # 给视图对象添加user属性,以便于在合并购物车时候使用到user对象
        self.context['view'].user = user
        OAuthQQUser.objects.create(user=user, openid=openid)

        # 由服务器生成一个jwt token，保存用户的身份信息
        from rest_framework_jwt.settings import api_settings

        # 生成载荷
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 给user增加属性token
        user.token = token

        return user


class UserCenterInfoSerializer(serializers.ModelSerializer):
    """用户中心个人信息序列化类"""

    class Meta:
        model = User
        fields = ('id', 'mobile', 'username', 'email', 'email_active')